
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import fr.opensagres.xdocreport.document.textstyling.html.HTMLTextStylingTransformer;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

public class WordToHtml {

    public static void main(String argv[]) throws Exception{
        docxToHtml("考试题.docx", "考试题1.html", "D:\\test");
        docToHtml("D:\\test\\doc文档转html.doc", "D:\\test\\doc文档转html.html");
    }

    /**
     * doc 转换 html
     * @param inFileName word文件路径
     * @param outFileName html文件路径
     */
    public static void docToHtml(String inFileName, String outFileName){
        try {
            //新建word输入流
            FileInputStream source = new FileInputStream(new File(inFileName));
            //获取word对象
            HWPFDocument wordDocument = new HWPFDocument(source);
            //获取转换对象
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
            //解析word文档
            wordToHtmlConverter.processDocument(wordDocument);
            //得到html文档
            org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
            //新建DOM源
            DOMSource domSource = new DOMSource(htmlDocument);
            //实例化转化工厂
            TransformerFactory tf = TransformerFactory.newInstance();
            //获取转化器
            Transformer serializer = tf.newTransformer();
            //设置转换编码格式 utf-8
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            //输出结果树时是否可以添加额外的空格
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            //文件属性html
            serializer.setOutputProperty(OutputKeys.METHOD, "html");
            //新建输入流
            FileOutputStream fos = new FileOutputStream(new File(outFileName));
            StreamResult streamResult = new StreamResult(fos);
            //转换
            serializer.transform(domSource, streamResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * docx格式转html
     * @param inFileName word 路径
     * @param outFileName html 路径
     * @param catalogue
     */
    public static void docxToHtml(String inFileName, String outFileName, String catalogue){
        FileInputStream source = null;
        OutputStream target = null;
        try {
            String inPath = catalogue + File.separator + inFileName;
            String outPath = catalogue + File.separator + outFileName;
            // 待转换文档输入流
            source = new FileInputStream(new File(inPath));
            // 输出目标
            target = new FileOutputStream(outPath);
            // 转换配置
//            XHTMLOptions options = XHTMLOptions.create();
//            TODO
//            options.
            // 待转换的docx文档对象
            XWPFDocument doc = new XWPFDocument(source);
            // 转换成html
            XHTMLConverter.getInstance().convert(doc, target, null);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            // 关闭流
            close(source);
            close(target);
            //===================================================================================================
            //在新生成的html中发现head标签中没有设置编码格式，查找资料也没有找到在转换过程中添加编码格式的地方，
            //所以在新生成的html中通过jsoup组件写入<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
            //添加标签后，生成的文件格式有部分变化
            addHeadToHtml(outFileName);
        }
    }

    /** 修改html中的head标签 */
    public static void addHeadToHtml(String filePath){
        File input = new File(filePath);
        Document doc = null;
        try {
            //添加编码格式
            doc = Jsoup.parse(input, "UTF-8");
            doc.head().append("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">");
            //======================================================================================================
            //输出新文件
            deleteFile(filePath);
            FileOutputStream fos = new FileOutputStream(filePath, true);
            fos.write(doc.html().getBytes());
            fos.close();
//=======================================================================================================
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath)
    {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists())
        {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 关闭输入流
     * @param is
     */
    private static void close(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭输出流
     * @param os
     */
    private static void close(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
